/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.web.freemark.tags;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;

/**
 * 
 * @author max.zheng
 * @create 2015-4-25下午9:26:02
 * @since 1.0
 * @see
 */
public class ComboGridTag extends DataGridTag {
//	<input id="cc" name="dept" value="01">
//	$('#cc').combogrid({
//	    panelWidth:450,
//	    value:'006',
//	 
//	    idField:'code',
//	    textField:'name',
//	    url:'datagrid_data.json',
//	    columns:[[
//	        {field:'code',title:'Code',width:60},
//	        {field:'name',title:'Name',width:100},
//	        {field:'addr',title:'Address',width:120},
//	        {field:'col4',title:'Col41',width:100}
//	    ]]
//	});

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-4-25下午9:26:20
	 * @modified by
	 * @param env
	 * @param params
	 * @param body
	 * @throws IOException
	 * @throws TemplateException
	 */
	@Override
	public void render(Environment env, Map params, TemplateDirectiveBody body)
			throws IOException, TemplateException {
		try {
			StringBuffer sb = new StringBuffer();
			String className = params.get("item").toString();
			String id = params.get("id")==null?UUID.randomUUID().toString():params.get("id").toString();
			String name = params.get("name")==null?"none":params.get("name").toString();
			String width = params.get("width")==null?"300":params.get("width").toString();
			sb.append("<script type=\"text/javascript\">")
			  .append("$(function() {")
			  .append("$('#"+id+"').combogrid({")
			  .append(addProperties("url", params.get("url"), true))
			  .append(addProperties("required", params.get("required"),false, false))
			  .append(addProperties("idField", params.get("idField"),"code", true))
			  .append(addProperties("textField", params.get("textField"),"name", true))
			  .append(addProperties("value", "["+params.get("values")+"]","[]", false))
			  .append(addProperties("multiple", params.get("multiple"),false,false))//默认单选
//			  .append(addProperties("multiple", true,false))//此处一直都是多选，为了解决下拉数必须要有checkbox
	  		  .append(addProperties("disabled", params.get("disabled")==null?"false":params.get("disabled"), false))
			  .append(addkeyHandler(params.get("keyword"),id))
	  		  .append(addEvent(params,id))
			  .append(createColumns(className,"id".equals(params.get("idField")),null,false))
			  .append("});")
			  //初始化回填
			  .append("$('#"+id+"hidden').val("+(params.get("values")==null?"":params.get("values"))+");")
			  .append("});")
			  .append("</script>");
		   sb.append("<input id=\""+id+"\" name=\""+name+"\" style=\"width:"+width+"px\"/>")
		   	 .append("<input id=\""+id+"hidden\" name=\""+name+"\" type=\"hidden\" />");
			writeBody(env, sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 新增列表控件可以設置查詢自動搜索
	 * @return
	 */
	private String addkeyHandler(Object keyword,String id) {
		StringBuffer sb = new StringBuffer();
		sb.append("keyHandler: {")
          .append("enter: function () {")
          .append("$('#opeatorCombogrid').combogrid('hidePanel');")  
          .append("},")
          .append("query: function (keyword) {")
          .append("var queryParams = $('#"+id+"').combogrid(\"grid\").datagrid('options').queryParams;")  
          .append(keyword==null?"queryParams.keyword = keyword;":"queryParams."+keyword+" = keyword;")  
          .append("$('#"+id+"').combogrid(\"grid\").datagrid(\"reload\");")
          .append("$('#"+id+"').combogrid(\"setValue\", keyword);") 
          .append("},")
          .append("},");
		return sb.toString();
}
	/**
	 * 添加事件相关操作
	 * @author max.zheng
	 * @create 2014-9-29下午9:23:33
	 * @modified by
	 * @param params
	 * @return
	 */
	private String addEvent(Map params,String id) {
		StringBuffer sb = new StringBuffer();
		sb.append("onChange : function(a, b) {")
		  .append("$('#"+id+"hidden').val( $('#"+id+"').combogrid('getValues'));");
		if (params.get("onChange")!=null) {
			sb.append(params.get("onChange")+";");
		}
		sb.append("},");
		if (params.get("onSelect")!=null) {
			sb.append("onSelect: function(index,row){"+params.get("onSelect")+";},");
		}
//		//设置单选下拉树情况下，只能选中一个对象控制
//		if ("false".equals(params.get("multiple")+"")) {
//			//单选情况
//			sb.append("onBeforeCheck:function(node,checked){")
//			  .append("var t =$('#"+id+"').combotree('tree');")
//			  .append("var nodes =t.tree('getChecked');")
//			  .append("for (var i = 0; i < nodes.length; i++) {")
//			  .append("if(nodes[i].id!=node.id) {")
//			  .append(" t.tree('uncheck',nodes[i].target);")
//			  .append("}}},");
//		}
		
		return sb.toString();
	}

}
